//
//  QDLargeTitleTableHeaderView.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/2/22.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit

/// 默认的高度,46
let QDLargeTitleTableHeaderViewNormalHeight = CGFloat(12 + 34)

/// 模拟的大标题
class QDLargeTitleTableHeaderView: UIView {
    
    /// 用于设置titleLabel的text
    var title: String = "" {
        willSet {
            titleLabel.text = newValue
        }
    }

    /// 大标题的label
    let titleLabel = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        titleLabel.font = Font.semibold.font(size: 24)
        titleLabel.textColor = QDColors.separator
    
        addSubview(titleLabel)
        makeAllConstraints()
    }
    
    
    /// 添加所有的子视图约束
    func makeAllConstraints(){
        
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(1)
            make.left.equalToSuperview().offset(20)
            make.height.equalTo(33)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


/// QDLargeTitleTableHeaderView容器
protocol QDLargeTitleTableHeaderContainer{
    
    associatedtype QDLargeTableHeaderView: QDLargeTitleTableHeaderView
    
    var largeTableHeaderView: QDLargeTableHeaderView { get }
}


/// 滚动时item变化的协议
protocol QDLargeTitleTableHeaderScrollable: QDLargeTitleTableHeaderContainer {
    
    /// 临街判定点
    var stagnationPointY: CGFloat { get }
    /// tableView进行变化,返回值告知是否已经显示item.title
    func tableViewDidScroll(contentOfset: CGPoint, complete: (Bool)->())
}


extension QDLargeTitleTableHeaderScrollable {
    
    var stagnationPointY: CGFloat { return BarDistance.NavigationBar.height - 1 - 33 + 4/*4为底部边距*/}
    func tableViewDidScroll(contentOfset: CGPoint,  complete: (Bool)->()) {}//默认不做任何处理
}



extension QDLargeTitleTableHeaderScrollable where Self: UIViewController {
    
    func tableViewDidScroll(contentOfset: CGPoint,  complete: (Bool)->()) { //根据偏移量

        if contentOfset.y >= -1 * stagnationPointY && navigationItem.title == nil {//显示
            navigationItem.title = largeTableHeaderView.titleLabel.text
            complete(true); return;
        }
        
        if contentOfset.y < -1 * stagnationPointY  && navigationItem.title != nil {//隐藏
            navigationItem.title = nil;
            complete(false); return
        }
    }
}

